/*
 *   Copyright 2008 Francois Fernandes
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.googlecode.opendoclibrary.server.internal;

import java.util.Hashtable;

import org.eclipse.osgi.framework.console.CommandProvider;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.util.tracker.ServiceTracker;

import com.googlecode.opendoclibrary.library.spi.ILibrary;

/**
 * The activator class controls the plug-in life cycle
 */
public class OpenDocLibraryServerActivator implements BundleActivator
{

    // The plug-in ID
    public static final String PLUGIN_ID = "com.googlecode.opendoclibrary.server.core";

    // The shared instance
    private static OpenDocLibraryServerActivator plugin;

    private ServiceTracker libraryTracker;

    private CommandLineExtensions cmdlineExtensions;

    /**
     * The constructor
     */
    public OpenDocLibraryServerActivator()
    {
    }

    public void start( BundleContext context ) throws Exception
    {
        plugin = this;

        cmdlineExtensions = new CommandLineExtensions( context );
        context.registerService( CommandProvider.class.getName(), cmdlineExtensions, new Hashtable<String, String>() );

        // library tracker
        Filter libraryFilter =
            context.createFilter( ( "(&(objectClass=" + ILibrary.class.getName() + ")(" + ILibrary.NAME + "=*))" ) );
        libraryTracker = new ServiceTracker( context, libraryFilter, new LibraryInstanceTracker( context ) );
        libraryTracker.open();

    }

    public void stop( BundleContext context ) throws Exception
    {
        if ( cmdlineExtensions != null )
            cmdlineExtensions.close();
        if ( libraryTracker != null )
            libraryTracker.close();
        libraryTracker = null;
        plugin = null;
    }

    /**
     * Returns the shared instance
     * 
     * @return the shared instance
     */
    public static OpenDocLibraryServerActivator getDefault()
    {
        return plugin;
    }

}
